//
//  HWUserInfo.m
//  嗨文
//
//  Created by 响当当 on 2019/3/20.
//  Copyright © 2019年 dongzheng. All rights reserved.
//

#import "HWUserInfo.h"

static HWUserInfo *_user = nil;

#define LCUserTable @"hwUserList"

@implementation HWUserInfo
+ (HWUserInfo *)currentUser
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (!_user) {
            _user = [[HWUserInfo alloc]init];
            if (![lcDBOperation lc_isExistTable:LCUserTable]) {
                [lcDBOperation lc_createTable:LCUserTable dicOrModel:self];
            }else
            {
                [_user getCurrentUserInfo];
            }
        }
    });
    return _user;
}

#pragma 获取当前用户信息  仅一个登陆用户
- (void)getCurrentUserInfo
{
    NSString *loginUserName = IFNULL(LCUserDefaultsGet(kLoginUser), @"");
    if ([loginUserName isEqualToString:@""])
    {
        NSLog(@"暂无用户信息");
    }else
    {
        NSString *sql = [NSString stringWithFormat:@"where username = %@",loginUserName];
        NSArray *userList = [lcDBOperation lc_lookupTable:LCUserTable dicOrModel:self whereFormat:sql];
        if (userList.count > 0) {
            _user = (HWUserInfo *)(userList.firstObject);
        }
    }
}


-(void)savaSessionSucess:(void(^)(void))sucess fail:(void(^)(NSError *error))fail
{
    
    
    if ([current_User isExistUser]) {
        [current_User refreshUserInfoSucess:^{
            if (sucess) {
                sucess();
            }
//            [APNsManager setAlias];
        } fail:^(NSError *error) {
            NSLog(@"刷新用户信息失败");
        }];
    }else
    {
        BOOL insertUserIsSucess = [lcDBOperation lc_insertTable:LCUserTable dicOrModel:current_User];
        if (insertUserIsSucess) {
            if (sucess) {
                sucess();
            }
//            [APNsManager setAlias];
        }else
        {
            [SVProgressHUD showErrorWithStatus:@"登录失败请重试"];
            DISMISS_SVP(1.5f);
            NSError *error = nil;
            if (fail) {
                fail(error);
            }
        }
    }
}

-(BOOL)isExistUser
{
    NSString *sql = [NSString stringWithFormat:@"where username = %@",current_User.username];
    NSArray *datas = [lcDBOperation lc_lookupTable:LCUserTable dicOrModel:self whereFormat:sql];
    if (datas.count > 0) {
        return true;
    }else
    {
        return false;
    }
}

#pragma 重新登录刷新用户信息
- (void)refreshUserInfoSucess:(void(^)(void))sucess fail:(void(^)(NSError *error))fail
{
    NSString *sql = [NSString stringWithFormat:@"where username = %@",current_User.username];
    if ([lcDBOperation lc_updateTable:LCUserTable dicOrModel:current_User whereFormat:sql]) {
        if (sucess) {
            sucess();
        }
    }else
    {
        if (fail) {
            NSError *error = nil;
            fail(error);
        }
    }
    
}
@end
